package cn.joeg.app.web.core.def;

import cn.joeg.app.web.core.vo.WidgetDataReq;
import cn.joeg.app.web.core.vo.WidgetDataResp;
import com.ecfront.dew.common.JsonHelper;
import com.ecfront.dew.common.Resp;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public abstract class AbstractWidgetAdapter implements BasicWidgetAdapter {

//    @Autowired
//    private WidgetDefRepository widgetDefRepository;

//    @Autowired
//    private CSSWidgetConfig cssWidgetConfig;

    private Map<String, Object> widgetMap = new HashMap<>();

    @PostConstruct
    @Override
    public void loadConfig() {

    }


    // 线程计数
//     private static AtomicInteger threadNum = new AtomicInteger(0);

    @Override
    public Resp<WidgetDataResp> dispatch(WidgetDataReq req) throws InvocationTargetException, IllegalAccessException {

        if (req.getWidgetMethod() == null || req.getWidgetMethod().isEmpty()) {
            req.setWidgetMethod("defaultMethod");
        }
        logger.info("[Widget] Dispatch [{}]-{}", req.getWidgetCode(), req.getWidgetMethod());
        Date time = new Date();
        if (!methods.containsKey(req.getWidgetCode() + ":" + req.getWidgetMethod())) {
            Method method = Arrays.stream(this.getClass().getDeclaredMethods()).filter(i -> i.getName().equals(req.getWidgetMethod())).findAny().get();
            methods.put(req.getWidgetCode() + ":" + req.getWidgetMethod(), method);
        }
        Method method = methods.get(req.getWidgetCode() + ":" + req.getWidgetMethod());

        logger.info("method: {}, req VO : {}", method.toString(), JsonHelper.toJson(req));
        Resp<WidgetDataResp> resp;
        if (method.getParameterTypes() != null && method.getParameterTypes().length > 0) {
            resp = (Resp<WidgetDataResp>) method.invoke(this, JsonHelper.toObject(req.getArgs(), method.getParameterTypes()[0]));
        } else {
            resp = (Resp<WidgetDataResp>) method.invoke(this);
        }

        logger.info("[Widget] Dispatch [{}]-{} : use time : {}", req.getWidgetCode(), req.getWidgetMethod(), new Date().getTime() - time.getTime());

        return resp;
    }

}
